package controller;

import java.util.ArrayList;
import java.util.List;

import view.overlay.AssignableControlsOverlay;
import view.overlay.AssignableControlsOverlay.ReassignListener;

public class AssignableControlController extends Controller implements ReassignListener {
	
	private GameControl mControlToMap;
	private AllKeyGameControl mListenerControl;
	
	private ControlConfiguration mConfig;
	
	private AssignableControlsOverlay mOverlay;
	
	public AssignableControlController(ControlConfiguration config, AssignableControlsOverlay overlay) {
		mConfig = config;
		mOverlay = overlay;
		
		// Register the controller to the overlay
		overlay.register(this);
		
		mListenerControl = new AllKeyGameControl("KEY_MAPPER") {
			
			public void execute(int keyCode) {
				if (this.isEnabled()) {
					// reassign
					finishReassign(mControlToMap, keyCode);
				}
			}
			
		};
		mListenerControl.setReassignable(false);
		mListenerControl.setEnabled(false);
		
		mOverlay.setVisible(false);
	}

	@Override
	public List<GameControl> getKeyControls() {
		List<GameControl> controls = new ArrayList<GameControl>();
	
		controls.add(mListenerControl);
		
		return (controls);
	}
	
	public void showControls() {
		mOverlay.setVisible(true);
		// Set the controls
		List<GameControl> assignableCtrls = new ArrayList<GameControl>();
		
		for (GameControl ctrl : mConfig.getAllControls()) {
			if (ctrl.isReassignable()) {
				assignableCtrls.add(ctrl);
			}
		}
		mOverlay.setControls(assignableCtrls);
		
	}
	
	public void hideControls() {
		mOverlay.setVisible(false);
	}

	@Override
	public void startReassign(GameControl control) {
		mControlToMap = control;
		mListenerControl.setEnabled(true);
	}
	
	private void finishReassign(GameControl control, int keyCode) {
		// Disable our listener
		mListenerControl.setEnabled(false);
		
		
		// See if there are any controls with this key
		List<GameControl> curKeyMappings = mConfig.getAllControlsMappedTo(keyCode);
		
		int currKeyCode = control.getActionCode();
		
		for (GameControl gc : curKeyMappings) {
			mConfig.reassign(gc.getId(), currKeyCode);
			mOverlay.finishAssign(gc);
		}
		
		// Reassign the control
		mConfig.reassign(control.getId(), keyCode);
		
		// Let the overlay know to go back to normal state
		mOverlay.finishAssign(control);
	}

	@Override
	public void exit() {
		// exit the menu
		hideControls();
		
	}
	
	public void reset() {
		mOverlay.setVisible(false);
	}
	
	

}
